package com.mac.bluetoothbt.feature;

import java.util.ArrayList;
import java.util.List;

import static com.mac.bluetoothbt.feature.FrameUtil.sendafterallwrite;

class WriteRegistersGenerator {
    private List<byte[]> writeCmdList;
    private byte[] registers, originRegisters;

    WriteRegistersGenerator(DeviceEntity deviceEntity, DeviceEntity originDeviceEntity) {
        registers = deviceEntity.getRegisters();
        originRegisters = originDeviceEntity.getRegisters();
        writeCmdList = new ArrayList<>();
        for (int i = 3; i < 183; i += 2) {
            if (registers[i] != originRegisters[i] ||
                    registers[i + 1] != originRegisters[i + 1]) {
                int regstart = (i - 3) / 2 + 1;
                if (is32(regstart)) {
                    if (regstart % 2 == 1) {
                        i += 2;
                    }
                    regstart = ((regstart + 1) / 2 * 2) - 1;
                    byte[] regBytes1 = FrameUtil.getWriteReverseRegisterFrame(registers, regstart, regstart);
                    writeCmdList.add(regBytes1);
                    byte[] regBytes2 = FrameUtil.getWriteReverseRegisterFrame(registers, regstart + 1, regstart + 1);
                    writeCmdList.add(regBytes2);
                } else {
                    byte[] regBytes = FrameUtil.getWriteRegisterFrame(registers, regstart, 1);
                    writeCmdList.add(regBytes);
                }
            }
        }
        writeCmdList.add(sendafterallwrite);
    }

    private boolean is32(int reg) {
        if (reg >= 13 && reg <= 18) {
            return true;
        } else if (reg >=23 && reg <= 28) {
            return true;
        } else if (reg >= 33 && reg <= 38) {
            return true;
        } else if (reg >= 63 && reg <= 68) {
            return true;
        } else if (reg >= 73 && reg <= 78) {
            return true;
        } else {
            return reg >= 83 && reg <= 88;
        }
    }

    List<byte[]> getWriteRegisterFrames() {
        return this.writeCmdList;
    }
}
